package com.example.dbsample.service.impl;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfig;
import com.example.dbsample.service.ConsumerExecutorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ConsumerExecutorServiceImpl implements ConsumerExecutorService {

    @ApolloConfig
    private Config config;

    /**
     * 开关是否开启
     */
    private boolean consumerInit = true;

    /**
     * 防止并发修改开关
     * @return
     */
    @Override
    public synchronized boolean execute() {
        boolean result;
        // 开关打开
        Boolean booleanProperty = config.getBooleanProperty("test_apollo_switch", true);
        if(Boolean.TRUE.equals(booleanProperty)) {
            result = startConsumer();
        } else {
            result = stopConsumer();
        }

        return result;
    }

    /**
     * 启动消费者
     */
    private boolean startConsumer() {
        boolean result = false;
        if(!consumerInit) {
            // TODO 补充业务代码
            consumerInit = true;
            result = true;
        } else {
            System.out.println("startConsumer do nothing");
        }
        return true;
    }

    /**
     * 关闭消费者
     */
    private boolean stopConsumer() {
        boolean result = false;
        if(consumerInit) {
            // TODO 补充业务代码
            consumerInit = false;
            result = true;
        } else {
            System.out.println("stopConsumer do nothing");
        }
        return true;
    }
}
